#! /usr/bin/env lfe
;; -*- mode: lfe -*-
;;! -smp enable -sname factorial -mnesia debug verbose
;;
;; Copyright (c) 2013-2020 Duncan McGreggor <oubiwann@gmail.com>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

;; File    : sample-lfescript
;; Author  : Robert Virding and Duncan McGreggor
;; Purpose : Demonstrating usage of lfe

;; To use this script make sure you have run "make install" from the
;; lfe working directory and then (temporarily) set the PATH:
;;
;; At this point, you can call this script directly:
;;
;;  $ export PATH=$(pwd)/bin:$PATH
;;  $ examples/sample-lfe-shellscript
;;  usage: examples/sample-lfescript <integer>
;;
;; As you can see, calling the script like that displays the usage statement.
;; Now call the script as intended, like the usage says:
;;
;;  $ examples/sample-lfe-shellscript 12
;;  factorial 12 = 479001600

(defun fac
  ([0] 1)
  ([n] (* n (fac (- n 1)))))

(defun usage ()
  (lfe_io:format "usage: ~s <integer>\n" (list script-name)))

;; Now do it
(case script-args
  ((cons string _)
   (try
       (let* ((n (list_to_integer string))
              (f (fac n)))
         (lfe_io:format "factorial ~w = ~w\n" (list n f)))
     (catch
       ((tuple _ _ _) (usage)))))
  (() (usage)))
